package com.shujia.day19;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;

public class Demo01FastJson {
    public static void main(String[] args) throws IOException {
        /*
            TODO 将HashMap中的KeyValue数据转换成Json格式
         */
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("key1","value1");
        hashMap.put("key2","value2");
        hashMap.put("key3","value3");
        JSONObject jsonObject1 = new JSONObject(hashMap);
        System.out.println(jsonObject1);// {"key1":"value1","key2":"value2","key3":"value3"}
        String jsonStr = "{\"key1\":\"value1\",\"key2\":\"value2\",\"key3\":\"value3\"}";
//        JSONObject jsonObject2 = new JSONObject();
//        jsonObject2.
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        System.out.println(jsonObject);

        // TODO 读取JSON文件
        //  1.通过IO流读取所有数据，再将数据传入JSONObject
        BufferedReader bufferedReader = new BufferedReader(new FileReader("src/com/shujia/day19/demo1.json"));
        String allJson = "";
        String readLine=null;
        while ((readLine = bufferedReader.readLine())!=null){
            allJson += readLine;
        }
        bufferedReader.close();
        JSONObject jsonObject2 = JSONObject.parseObject(allJson);
        System.out.println(jsonObject2);

        String name = jsonObject2.getString("name");
        Integer anInt = jsonObject2.getInteger("int");
        Double anDouble = jsonObject2.getDouble("double");
        JSONObject moreJson = jsonObject2.getJSONObject("moreJson");
        System.out.println(name);
        System.out.println(anInt);
        System.out.println(anDouble);
        System.out.println(moreJson);

        // JSON数组
        JSONArray moreArrJson = jsonObject2.getJSONArray("moreArrJson");
        for (int i = 0; i < moreArrJson.size(); i++) {
            JSONObject json = moreArrJson.getJSONObject(i);
            System.out.println(json.get("name"));
            System.out.println(json.get("age"));
        }
        JSONArray moreArr = jsonObject2.getJSONArray("moreArr");
        for (int i = 0; i < moreArrJson.size(); i++) {
            Object o = moreArr.get(i);
            System.out.println(o);
        }





    }
}
